/**
 * 域名 全局属性
 */

const BASE_URL1 = "https://service.xiaokanglongjiang.com/essc";//服务器1

// const BASE_URL2 = 'https://u345171z68.imdo.co';//服务器2
const BASE_URL2 = 'https://service2.ediblefungus.cn/api';//服务器2
// const BASE_URL2 = 'http://nforce.iask.in';//服务器2
// const BASE_URL2 = 'http://192.168.10.84:8082';//服务器2
// const BASE_URL2 = "http://14e502668g.zicp.fun";//服务器2
// const BASE_URL2 = "http://j145026q68.vicp.fun";//服务器2
// const BASE_URL2 = "http://vvc-china.qicp.vip";//服务器2
// const BASE_URL4 = "https://3451m7y168.goho.co";//服务器2
const BASE_URL4 = "https://service2.ediblefungus.cn";

const BASE_URL3 = "";//生成页面时服务器域名

const BASE_IMG = "https://service2.ediblefungus.cn/Image/"
const BASE_ICON = "https://service2.ediblefungus.cn/admin/icons/"
// const Domain_Business = "http://127.0.0.1:8080/svysj/business"

// const BASE_ICON = "http://127.0.0.1:8080/svysj/img"

const sumberError = "校验失败，请检查异常字段！";//校验失败提示。
const BusinessPreview = "BASE00000000004";//业务预览主键

/**
 * 第三方身份配置  supplier:供应商
 * @returns 
 */
const tripartite = { 'supplier': 'admin/data/supplierMenu.json', 'firstparty': 'admin/data/firstpartyMenu.json' }

/**
 * 获取cookie中内容
 * @param {String} Key 
 * @returns 
 */
const getCookie = function (key) {
    return $.cookie(key);
}

/**
 * 保存cookie中内容
 * @param {String} Key 
 * @returns 
 */
const setCookie = function (key, value) {
    return $.cookie(key, value);
}

/**
 * 移除cookie中内容
 * @param {String} Key 
 * @returns 
 */
const removeCookie = function (key) {
    return $.removeCookie(key);
}

/**
 * 获取当前Ip地址
 * @returns 
 */
const getIpAddress = function () {
    let str = "";
    $.ajax({
        url: `${BASE_URL1}/svysj/getIPAction`,
        type: 'GET',
        async: false,
        success: function (IP) {
            str = IP;
        },
        dataType: "text"
    });
    return str;
}

/**
 * 获取字段配置信息
 * @param {String} HTMLNAME 
 */
const getField = function (HTMLNAME, callback) {
    $.ajax({
        url: `${BASE_URL1}/GetRedis?Key=esscField${getCookie('user')}`,
        type: 'GET',
        success: function (Result) {
            if (Result.Status == "success") {
                if (HTMLNAME) {
                    const field = Result.Data[HTMLNAME];
                    if (field) {
                        callback(field);
                    } else {
                        callback([]);
                    }
                } else {
                    callback(Result.Data);
                }
            } else {
                if (HTMLNAME) {
                    callback([]);
                } else {
                    callback({});
                }
            }
        },
        dataType: "json"
    });
}

/**
 * 更新字段配置信息
 * @param {String} HTMLNAME 
 * @param {Array} FIEIDS 
 */
const setField = function (HTMLNAME, FIELDS, callback) {
    getField(null, (fieldObj) => {
        fieldObj[HTMLNAME] = FIELDS;
        $.ajax({
            url: `${BASE_URL1}/RedisAdd`,
            type: 'POST',
            data: {
                Key: 'esscField' + getCookie('user'),
                Main: JSON.stringify(fieldObj),
            },
            success: function (Result) {
                callback(Result)
            },
            dataType: "json"
        });
    })
}

/**
 * 生成日志
 * @param {String} Operation_Name 日志说明
 * @param {String} Operation_Type 操作类型
 * @param {String} Table_Name 操作表名
 * @param {String} Operation_Main 提交数据
 * @returns 
 */
const generateLog = function (Operation_Name, Operation_Type,Table_Name, Operation_Main='') {
    return {
        Operation_SerialNumber: '',
        Operation_Name,
        Operation_Type,
        Table_Name,
        Operation_Main,
        Operation_IP: getIpAddress(),
    }
}

/**
 * 请求头配置
 * @param {enum} Type 
 * @returns 
 */
const requestHeaders = function (Type = "FORM") {
    let ContentType;
    switch (Type) {
        case "FORM":
            ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
            break;
        case "JSON":
            ContentType = "application/json;charset=UTF-8";
            break;
        case "XML":
            ContentType = "text/html;charset=UTF-8";
            break;
    }
    return {
        'Content-Type': ContentType,
        AccessToken: getCookie('token')
    }
}

/**
 * 响应预处理
 * @param {XMLHttpRequest} XMLHttpRequest 
 * @param {*} user 账号 
 */
const requestPretreatment = function (XMLHttpRequest, user = false, callback) {
    if (XMLHttpRequest.status == 200) { //成功
        const token = XMLHttpRequest.getResponseHeader("ACCESSTOKEN")
        if (token) {//是否有Token
            setCookie('token', token);
            if (user) {//是否登录
                $.ajax({//登录日志
                    headers: requestHeaders(),
                    url: `${BASE_URL2}/generalBusiness/generalSave`,
                    type: 'POST',
                    data: {
                        Data: JSON.stringify({ Add: { base_system_login_log: [{ IP: getIpAddress() }] } })
                    },
                    complete: function () {
                        setCookie('user', user);
                        //获取用户身份信息
                        $.ajax({
                            headers: requestHeaders(),
                            url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
                            type: 'POST',
                            data: {
                                SQLSerialNumber: 'A_base_system_user_role',
                                Condition: window.btoa(unescape(encodeURIComponent(user))),
                                ExtensionCondition: '',
                            },
                            success: function (Result) {
                                if (Result.length > 0) {//有身份
                                    let specialRole = [];
                                    for (let key in tripartite) {
                                        if (Result.some(item => item.Role_SerialNumber == key)) {
                                            specialRole.push(Result.filter(item => item.Role_SerialNumber == key)[0])
                                        }
                                    }
                                    //判断是否为第三方身份，目前第三方身份仅供应商，默认跳转到指定页面
                                    if (specialRole.length == 1) {//跳转到第三方页面
                                        let Role = specialRole[0];
                                        setCookie('role', JSON.stringify({ data: tripartite[Role.Role_SerialNumber], role: Role.Role_SerialNumber, other: Role.Other_SerialNumber }));
                                    }
                                }
                                window.parent.document.location.href = './index.html';
                            },
                            complete: function (XMLHttpRequest) {
                                requestPretreatment(XMLHttpRequest);
                            },
                            dataType: "json"
                        });
                    },
                    dataType: "json"
                })
            }
        }
    } else if (XMLHttpRequest.status == 302) { //重定向
        const redirect = XMLHttpRequest.getResponseHeader("REDIRECT");
        if (redirect) {
            if (user) {
                callback ? callback('error') : null;
            } else {
                removeCookie('token');
                removeCookie('user');
                sessionStorage.setItem('REDIRECT', '登录已过期，请重新登录！')
                window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
            }
        }
    } else if (XMLHttpRequest.status == 500) { //
        callback ? callback('error') : null;
    } else if (XMLHttpRequest.status == 404) {
        callback ? callback('error') : null;
    }
}